package com.monitor.ui.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.cell.ProgressBarTableCell;
import javafx.util.Callback;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.File;
import java.awt.Desktop;
import java.io.IOException;

/**
 * 资源中心控制器
 * 负责资源下载和管理功能的实现
 */
public class ResourcePanelController implements Initializable {

    // 资源下载相关组件
    @FXML private TextArea resourceDescription;
    @FXML private ComboBox<String> resourceCategoryCombo;
    @FXML private TextField searchField;
    @FXML private TableView<Resource> resourceTableView;
    @FXML private TableColumn<Resource, String> nameColumn;
    @FXML private TableColumn<Resource, String> categoryColumn;
    @FXML private TableColumn<Resource, String> sizeColumn;
    @FXML private TableColumn<Resource, String> dateColumn;
    @FXML private TableColumn<Resource, Button> downloadColumn;
    @FXML private Label statusLabel;
    @FXML private Button refreshBtn;
    
    // 下载管理相关组件
    @FXML private TableView<DownloadTask> downloadTableView;
    @FXML private TableColumn<DownloadTask, String> downloadNameColumn;
    @FXML private TableColumn<DownloadTask, Double> progressColumn;
    @FXML private TableColumn<DownloadTask, String> speedColumn;
    @FXML private TableColumn<DownloadTask, String> statusColumn;
    @FXML private TableColumn<DownloadTask, Button> actionColumn;
    @FXML private Button clearCompletedBtn;
    @FXML private Button openDownloadFolderBtn;
    
    // 数据模型
    private ObservableList<Resource> resourceList = FXCollections.observableArrayList();
    private FilteredList<Resource> filteredResources;
    private ObservableList<DownloadTask> downloadTasks = FXCollections.observableArrayList();
    
    // 下载文件夹路径
    private final String downloadFolderPath = System.getProperty("user.home") + File.separator + "Downloads";
    
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // 初始化资源分类下拉框
        initResourceCategories();
        
        // 初始化资源表格
        initResourceTable();
        
        // 初始化下载任务表格
        initDownloadTable();
        
        // 加载示例资源数据
        loadSampleResources();
        
        // 设置搜索功能
        setupSearch();
    }
    
    /**
     * 初始化资源分类下拉框
     */
    private void initResourceCategories() {
        ObservableList<String> categories = FXCollections.observableArrayList(
            "全部",
            "学习资料",
            "安全教育",
            "健康知识",
            "素质拓展",
            "科普读物"
        );
        resourceCategoryCombo.setItems(categories);
        resourceCategoryCombo.getSelectionModel().selectFirst();
    }
    
    /**
     * 初始化资源表格
     */
    private void initResourceTable() {
        // 设置列的单元格值工厂
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        categoryColumn.setCellValueFactory(new PropertyValueFactory<>("category"));
        sizeColumn.setCellValueFactory(new PropertyValueFactory<>("size"));
        dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
        
        // 设置下载按钮列
        downloadColumn.setCellFactory(param -> new TableCell<Resource, Button>() {
            private final Button downloadBtn = new Button("下载");
            
            @Override
            protected void updateItem(Button item, boolean empty) {
                super.updateItem(item, empty);
                
                if (empty) {
                    setGraphic(null);
                } else {
                    Resource resource = getTableView().getItems().get(getIndex());
                    downloadBtn.setOnAction(event -> downloadResource(resource));
                    setGraphic(downloadBtn);
                }
            }
        });
        
        // 设置表格数据
        filteredResources = new FilteredList<>(resourceList, p -> true);
        resourceTableView.setItems(filteredResources);
    }
    
    /**
     * 初始化下载任务表格
     */
    private void initDownloadTable() {
        // 设置列的单元格值工厂
        downloadNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        progressColumn.setCellValueFactory(new PropertyValueFactory<>("progress"));
        speedColumn.setCellValueFactory(new PropertyValueFactory<>("speed"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
        
        // 设置进度条列
        progressColumn.setCellFactory(ProgressBarTableCell.forTableColumn());
        
        // 设置操作按钮列
        actionColumn.setCellFactory(param -> new TableCell<DownloadTask, Button>() {
            private final Button actionBtn = new Button();
            
            @Override
            protected void updateItem(Button item, boolean empty) {
                super.updateItem(item, empty);
                
                if (empty) {
                    setGraphic(null);
                } else {
                    DownloadTask task = getTableView().getItems().get(getIndex());
                    
                    if ("暂停".equals(task.getStatus())) {
                        actionBtn.setText("继续");
                        actionBtn.setOnAction(event -> resumeDownload(task));
                    } else if ("下载中".equals(task.getStatus())) {
                        actionBtn.setText("暂停");
                        actionBtn.setOnAction(event -> pauseDownload(task));
                    } else if ("已完成".equals(task.getStatus())) {
                        actionBtn.setText("打开");
                        actionBtn.setOnAction(event -> openDownloadedFile(task));
                    } else {
                        actionBtn.setText("重试");
                        actionBtn.setOnAction(event -> retryDownload(task));
                    }
                    
                    setGraphic(actionBtn);
                }
            }
        });
        
        // 设置表格数据
        downloadTableView.setItems(downloadTasks);
    }
    
    /**
     * 加载示例资源数据
     */
    private void loadSampleResources() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        resourceList.addAll(
            new Resource("网络安全教育手册", "安全教育", "2.5 MB", dateFormat.format(new Date())),
            new Resource("健康上网指南", "健康知识", "1.8 MB", "2023-05-15"),
            new Resource("高中数学辅导教材", "学习资料", "15.6 MB", "2023-04-20"),
            new Resource("青少年心理健康读本", "健康知识", "3.2 MB", "2023-06-10"),
            new Resource("编程入门教程", "学习资料", "8.7 MB", "2023-03-05"),
            new Resource("科学实验指导", "科普读物", "5.4 MB", "2023-07-01"),
            new Resource("文学经典赏析", "素质拓展", "4.1 MB", "2023-02-18"),
            new Resource("防沉迷系统使用指南", "安全教育", "1.2 MB", "2023-08-12")
        );
        
        updateStatusLabel();
    }
    
    /**
     * 设置搜索功能
     */
    private void setupSearch() {
        searchField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredResources.setPredicate(resource -> {
                // 如果搜索框为空，显示所有资源
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }
                
                String lowerCaseFilter = newValue.toLowerCase();
                
                // 按名称搜索
                return resource.getName().toLowerCase().contains(lowerCaseFilter);
            });
            
            updateStatusLabel();
        });
    }
    
    /**
     * 更新状态标签
     */
    private void updateStatusLabel() {
        statusLabel.setText(String.format("共有%d个资源", filteredResources.size()));
    }
    
    /**
     * 分类选择事件处理
     */
    @FXML
    private void onCategorySelected() {
        String selectedCategory = resourceCategoryCombo.getValue();
        
        filteredResources.setPredicate(resource -> {
            // 如果选择"全部"，显示所有资源
            if ("全部".equals(selectedCategory)) {
                return true;
            }
            
            // 按分类筛选
            return resource.getCategory().equals(selectedCategory);
        });
        
        updateStatusLabel();
    }
    
    /**
     * 搜索按钮点击事件
     */
    @FXML
    private void onSearchClicked() {
        // 搜索功能已通过监听器实现
        // 这里可以添加额外的搜索逻辑
    }
    
    /**
     * 刷新按钮点击事件
     */
    @FXML
    private void onRefreshClicked() {
        // 模拟刷新操作
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("刷新资源");
        alert.setHeaderText(null);
        alert.setContentText("资源列表已刷新");
        alert.showAndWait();
    }
    
    /**
     * 清除已完成下载按钮点击事件
     */
    @FXML
    private void onClearCompletedClicked() {
        // 创建要删除的任务列表
        ObservableList<DownloadTask> tasksToRemove = FXCollections.observableArrayList();
        
        // 找出所有已完成的任务
        for (DownloadTask task : downloadTasks) {
            if ("已完成".equals(task.getStatus())) {
                tasksToRemove.add(task);
            }
        }
        
        // 删除已完成的任务
        downloadTasks.removeAll(tasksToRemove);
    }
    
    /**
     * 打开下载文件夹按钮点击事件
     */
    @FXML
    private void onOpenDownloadFolderClicked() {
        try {
            File downloadFolder = new File(downloadFolderPath);
            if (!downloadFolder.exists()) {
                downloadFolder.mkdirs();
            }
            
            Desktop.getDesktop().open(downloadFolder);
        } catch (IOException e) {
            e.printStackTrace();
            showAlert("错误", "无法打开下载文件夹: " + e.getMessage());
        }
    }
    
    /**
     * 下载资源
     */
    private void downloadResource(Resource resource) {
        // 创建新的下载任务
        DownloadTask task = new DownloadTask(resource.getName(), 0.0, "0 KB/s", "下载中");
        downloadTasks.add(task);
        
        // 模拟下载进度更新
        // 实际项目中应该使用后台线程和Task来实现
        new Thread(() -> {
            try {
                for (int i = 0; i <= 100; i += 5) {
                    final int progress = i;
                    javafx.application.Platform.runLater(() -> {
                        task.setProgress(progress / 100.0);
                        task.setSpeed((progress < 100) ? (progress * 10) + " KB/s" : "0 KB/s");
                        if (progress >= 100) {
                            task.setStatus("已完成");
                        }
                        downloadTableView.refresh();
                    });
                    Thread.sleep(500); // 模拟下载延迟
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
    
    /**
     * 暂停下载
     */
    private void pauseDownload(DownloadTask task) {
        task.setStatus("暂停");
        task.setSpeed("0 KB/s");
        downloadTableView.refresh();
    }
    
    /**
     * 继续下载
     */
    private void resumeDownload(DownloadTask task) {
        task.setStatus("下载中");
        task.setSpeed("150 KB/s"); // 模拟下载速度
        downloadTableView.refresh();
        
        // 实际项目中应该恢复下载线程
    }
    
    /**
     * 重试下载
     */
    private void retryDownload(DownloadTask task) {
        task.setStatus("下载中");
        task.setProgress(0.0);
        task.setSpeed("120 KB/s"); // 模拟下载速度
        downloadTableView.refresh();
        
        // 实际项目中应该重新启动下载线程
    }
    
    /**
     * 打开已下载文件
     */
    private void openDownloadedFile(DownloadTask task) {
        showAlert("打开文件", "尝试打开文件: " + task.getName());
        // 实际项目中应该打开下载的文件
    }
    
    /**
     * 显示提示对话框
     */
    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    /**
     * 资源类
     */
    public static class Resource {
        private final SimpleStringProperty name;
        private final SimpleStringProperty category;
        private final SimpleStringProperty size;
        private final SimpleStringProperty date;
        
        public Resource(String name, String category, String size, String date) {
            this.name = new SimpleStringProperty(name);
            this.category = new SimpleStringProperty(category);
            this.size = new SimpleStringProperty(size);
            this.date = new SimpleStringProperty(date);
        }
        
        public String getName() { return name.get(); }
        public String getCategory() { return category.get(); }
        public String getSize() { return size.get(); }
        public String getDate() { return date.get(); }
    }
    
    /**
     * 下载任务类
     */
    public static class DownloadTask {
        private final SimpleStringProperty name;
        private final SimpleDoubleProperty progress;
        private final SimpleStringProperty speed;
        private final SimpleStringProperty status;
        
        public DownloadTask(String name, Double progress, String speed, String status) {
            this.name = new SimpleStringProperty(name);
            this.progress = new SimpleDoubleProperty(progress);
            this.speed = new SimpleStringProperty(speed);
            this.status = new SimpleStringProperty(status);
        }
        
        public String getName() { return name.get(); }
        public Double getProgress() { return progress.get(); }
        public String getSpeed() { return speed.get(); }
        public String getStatus() { return status.get(); }
        
        public void setProgress(Double value) { progress.set(value); }
        public void setSpeed(String value) { speed.set(value); }
        public void setStatus(String value) { status.set(value); }
    }
}